package com.yc.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yc.pay.api.enums.PayChannelEnums;
import com.yc.pay.api.req.RefundReq;
import com.yc.pay.api.resp.RespVo;
import com.yc.pay.model.MchInfo;
import com.yc.pay.model.PaySerial;
import com.yc.pay.service.IMchService;
import com.yc.pay.service.IRefundService;
import com.yc.pay.utils.PayDigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Service
public class RefundServiceImpl implements IRefundService {

    @Autowired
    private IMchService mchService;


    @Override
    public RespVo createRefund(RefundReq refundReq) {

        //签名
        String sign = refundReq.getSign();
        Map map = JSONObject.parseObject(JSONObject.toJSONString(refundReq),Map.class);

        MchInfo mchInfo = mchService.queryByMchId(refundReq.getMchId());

        if(ObjectUtils.isEmpty(mchInfo)){
            return RespVo.returnFailRespVo("商户id不存在");
        }

        String newSign = PayDigestUtil.getSign(map,mchInfo.getReqKey(),"sign");

        if (!sign.equals(newSign)){
            return RespVo.returnFailRespVo("请求非法");
        }

        //检查流水号是否存在
        PaySerial paySerial = null; //paySerialService.queryByPaySerialNoOrMchOrderNo(refundReq.getPaySerialNo(),refundReq.getMchOrderNo());


        if (ObjectUtils.isEmpty(paySerial)){

            return RespVo.returnFailRespVo("支付流水号不存在");
        }

        //重复退款 接口幂等，唯一索引，token机制，分布式锁
/*        List<RefundSerial> refundSerialList = serialService.queryByPaySerialNo(refundReq.getPaySerialNo());


        for (RefundSerial refundSerial :refundSerialList){

            if ("1".equals(refundSerial.getRefundStatus()) || "2".equals(refundSerial.getRefundStatus())){
                return RespVo.getFailReturn("该笔交易存在退款申请，请稍后在试");
            }*/


            //判断退款金额不能大于原定单金额 数据库中，退款中 + 银行处理中 + 成功的 +　refundReq中金额 <= 订单金额       paySerial.getPayAmt()

        BigDecimal orderAmt = paySerial.getPayAmt();//100

        BigDecimal refunAmt = new BigDecimal(refundReq.getRefundAmt()); //20 +已经退款成功的记录

        int refundCount = 0;

    /*    for (RefundSerial refundSerial :refundSerialList) {

            if ("0".equals(refundSerial.getRefundStatus())){
                refundCount ++;
                refunAmt = refunAmt.add(refundSerial.getRefundAmount());
            }
        }*/

        //退款金额是否大于订单金额

        int rlt = refunAmt.compareTo(orderAmt);
        if (rlt<0){
            return RespVo.returnFailRespVo("退款金额不能超过订单金额");
        }

        //在退款时间内:
        int days =  7;//payConfig.getMaxRunfundDay();
        Date paySuccessTime = paySerial.getPaySuccessTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(paySuccessTime);
        calendar.add(Calendar.DAY_OF_MONTH, +days);
        Date finalDate = calendar.getTime();
        Date nowTime = new Date();
        if (nowTime.after(finalDate)){
            return RespVo.returnFailRespVo("已经超过退款期限");
        }

        //

        //是否超过50比退款
        if(refundCount >=50){
            return RespVo.returnFailRespVo("单笔交易最多支持50次退款");
        }


        // 生成退款流水。退款申请中
//        RefundSerial refundSerial = serialService.createRefundSerial(refundReq,paySerial);


        if(PayChannelEnums.ALIPAY.getCode().equals(refundReq.getPayChannel())){
            //springCloud 调用支付宝前置服务

            //返回结果，更新数据库的退款状态，支付宝只有成功失败


            //封装RespVo 对象返回

        } else if(PayChannelEnums.WECHAT.getCode().equals(refundReq.getPayChannel())){

            //springCloud 调用微信前置服务，

            //收到微信结果，更新状态为，银行处理中，或者失败。 异步

            //封装RespVo 对象返回

        }else{

        }



        return null;
    }
}
